package com.invengo.testrfid.mvp.presenter;

import android.app.Application;
import android.content.Context;

import com.invengo.testrfid.app.dao.QueryManager;
import com.invengo.testrfid.app.dao.RfidCageBind;
import com.invengo.testrfid.app.entity.ReadTagEntity;
import com.invengo.testrfid.app.proxy.ProxyReadTag;
import com.invengo.testrfid.app.utils.Constant;
import com.invengo.testrfid.app.utils.MyDialogueUtils;
import com.invengo.testrfid.app.utils.MyDialogueUtilsListenser;
import com.invengo.testrfid.app.utils.MyLogUtils;
import com.invengo.testrfid.app.utils.SoundPlayUtils;
import com.invengo.testrfid.app.utils.TimeUtilsNew;
import com.invengo.testrfid.app.utils.UUIDUtils;
import com.invengo.testrfid.mvp.contract.AddCageNewContract;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;


import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;


@ActivityScope
public class AddCageNewPresenter extends BasePresenter<AddCageNewContract.Model, AddCageNewContract.View> {
    private RxErrorHandler mErrorHandler;
    private Application mApplication;

    private ReadTagEntity firstReadTag;
    private AppManager mAppManager;
    private QueryManager queryManager;


    private ReadTagEntity readTagEntityOne;
    private ReadTagEntity readTagEntityTwo;

    @Inject
    public AddCageNewPresenter(AddCageNewContract.Model model, AddCageNewContract.View rootView
            , RxErrorHandler handler, Application application
            , AppManager appManager) {
        super(model, rootView);
        this.mErrorHandler = handler;
        this.mApplication = application;
        this.mAppManager = appManager;
        this.queryManager = QueryManager.getManager();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mApplication = null;
    }


    public void connect() {

        ProxyReadTag.getInstance().connectReader(new ProxyReadTag.ConnectReaderStatue() {
            @Override
            public void onConnectSuccess() {

            }

            @Override
            public void onConnectFailed() {

            }
        });
    }

    public void disConnect() {

        ProxyReadTag.getInstance().disConnectReader(new ProxyReadTag.DisConnectReaderStatue() {
            @Override
            public void onDisConnectSuccess() {

            }

            @Override
            public void onDisConnectFailed() {

            }
        });
    }


    public void onInputViewNextClick(Context context, String data) {

        if (data.trim().length() == 0) {
            mRootView.showMessage("集装箱编号不可以为空！");
            return;
        }

        final RfidCageBind rfidCageBind = queryManager.getRfidCageQuery().queryDataByCageNo(data);
        if (rfidCageBind != null) {

            // 弹出对话框，提示是否更新绑定关系
            MyDialogueUtils dia = new MyDialogueUtils(context);
            dia.setTitle("提示");
            dia.setBody("该集装箱编号已存在，是否更新绑定关系。如果更新绑定关系，" +
                    "之前的绑定记录将会被删除，请谨慎操作？");
            dia.setFoot("取消", "更新");
            dia.registerListenser(new MyDialogueUtilsListenser() {

                @Override
                public void onPositiveClick(String text) {

                    queryManager.getRfidCageQuery().delete(rfidCageBind);
                    mRootView.showSecondView();
                }

                @Override
                public void onNegetiveClick(String text) {

                    mRootView.showMessage("请输入新的集装箱编号");
                }
            });
            dia.showDia();
        } else {
            mRootView.showSecondView();
        }
    }


    private boolean isInitTagOne;

    /**
     * 读取标签
     */
    public void readTag(final String cageNo, boolean isInitTagOne) {

        this.isInitTagOne = isInitTagOne;
        ProxyReadTag.getInstance().singleReadTagTid(new ProxyReadTag.ReadTagAllDataCallbac() {
            @Override
            public void onReadTagSuccess(ReadTagEntity res) {

                firstReadTag = res;
            }

            @Override
            public void onReadTagFailed(String msg) {

            }
        }, new ProxyReadTag.StopReadCallback() {
            @Override
            public void onStopSuccess() {

                MyLogUtils.log("init", "readTagSuccess", 1);
                firstWriteTag(firstReadTag, cageNo);
            }

            @Override
            public void onStopFailed() {

            }
        });
    }


    /**
     * 存储数据
     *
     * @param cageID
     */
    public void saveData(String cageID) {

        // 存储到本地
        RfidCageBind rfidCageBindNew = new RfidCageBind();
        rfidCageBindNew.setId(UUIDUtils.getShortUUId());
        rfidCageBindNew.setTagId(readTagEntityOne.getTid() +
                Constant.ValueOfSpare + readTagEntityTwo.getTid());
        rfidCageBindNew.setCageId(cageID);
        rfidCageBindNew.setIsBind(false);
        rfidCageBindNew.setBindTime(TimeUtilsNew.getStringTimelByLong(System.currentTimeMillis()));
        rfidCageBindNew.setFailedMessage("");
        queryManager.getRfidCageQuery().insert(rfidCageBindNew);
        SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_SUCCESS, 2);
        mRootView.showMessage("数据存储成功");

        mRootView.showFirstView();
        mRootView.clearAllData();
        readTagEntityOne = null;
        readTagEntityTwo = null;
    }

    private void firstWriteTag(ReadTagEntity readTagEntity, String cageNo) {

        if (isInitTagOne) {

            if (readTagEntityTwo != null && readTagEntity.getTid().trim().equals(readTagEntityTwo.getTid().trim())) {
                mRootView.showMessage("读到的标签和初始化的第2张标签一致");
                SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_FAILED, 0);
                return;
            }
        } else {
            if (readTagEntityOne != null && readTagEntity.getTid().trim().equals(readTagEntityOne.getTid().trim())) {
                SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_FAILED, 0);
                mRootView.showMessage("读到的标签和初始化的第1张标签一致");
                return;
            }
        }

        RfidCageBind epc = queryManager.getRfidCageQuery().queryDataByCageNo(readTagEntity.getEpc());
        RfidCageBind tid = queryManager.getRfidCageQuery().queryDataByTid(readTagEntity.getTid());

//        if(true){
        if (epc == null && tid == null) {

            MyLogUtils.log("init", "begin write tag  ---  " + cageNo, 2);
            writeTag(readTagEntity, cageNo);
        } else {
            SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_FAILED, 0);
            MyLogUtils.log("init", "stop write tag", 1);
            mRootView.initReadTag(readTagEntity);
        }
    }

    private void writeTag(final ReadTagEntity readTagEntity, final String cageNo) {

        ProxyReadTag.getInstance().writeDataToEpc(
                readTagEntity.getTidData(),
                cageNo.trim().getBytes(),
                new ProxyReadTag.WriteTagEpcCallback() {
                    @Override
                    public void onWriteSuccess() {

                        MyLogUtils.log("init", "write tag success", 3);
                        readTagLast();
                    }

                    @Override
                    public void onWriteFailed() {
                        MyLogUtils.log("init", "write tag failed", 3);
                        mRootView.initReadTag(readTagEntity);
                    }
                });

    }

    
    private void readTagLast() {

        ProxyReadTag.getInstance().singleReadTagTid(new ProxyReadTag.ReadTagAllDataCallbac() {
            @Override
            public void onReadTagSuccess(ReadTagEntity readTagEntity) {


                if (isInitTagOne) {
                    readTagEntityOne = readTagEntity;
                } else {
                    readTagEntityTwo = readTagEntity;
                }

                MyLogUtils.log("init", "read tag 2 success", 4);
                SoundPlayUtils.getInstance().playSound(SoundPlayUtils.SOUNT_SUCCESS, 0);
                mRootView.initReadTag(readTagEntity);
            }

            @Override
            public void onReadTagFailed(String msg) {

            }
        }, new ProxyReadTag.StopReadCallback() {
            @Override
            public void onStopSuccess() {

            }

            @Override
            public void onStopFailed() {

            }
        });
    }


}
